from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
from django.contrib.auth.hashers import make_password,check_password

from .utils import send_message,MyAlipay,MyJwt
from .models import *
from .serializers import *
from shops.models import ShopsModel
from shops.serializers import *
from send.models import *
from send.serializers import *

import time,jwt,random,redis,datetime,json


# 发送短信验证码
class SmsCodeView(ViewSet):
    def smscode(self,request):
        mobile = request.data.get('mobile')

        sms_code = random.randint(10000,99999)
        expire = 5

        result = send_message(sms_code,mobile,expire)

        r = redis.Redis(host='localhost', port=6379, db=0)
        sms_key = 'sms_%s' % mobile
        r.set(sms_key, sms_code)

        return Response({'errcode':0,'msg':'短信验证码发送成功，请注意查收'})

# 用户视图
class UserViewSet(ViewSet):

    # 注册
    def register(self,request):

        nickname = request.data.get('nickname')
        mobile = request.data.get('mobile')
        password = request.data.get('password')
        code = request.data.get('code')

        try:
            if not [nickname,mobile,password,code]:
                return Response({'errcode':2,'msg':'用户信息不完整'})

            user = UserModel.objects.filter(nickname=nickname,is_delete=False).first()
            if user:
                return Response({'errcode':1,'msg':'用户已注册'})

            user = SendModel.objects.filter(nickname=nickname, is_delete=False).first()
            if user:
                return Response({'errcode':1,'msg':'用户已注册'})

            user = ShopsModel.objects.filter(nickname=nickname, is_delete=False).first()
            if user:
                return Response({'errcode': 1, 'msg': '用户已注册'})
            pwd = make_password(password,'pbkdf2_sha256')
            UserModel.objects.create(nickname=nickname, password=pwd, mobile=mobile, role_id=1)  # 默认普通用户
            return Response({'errcode':0,'msg':'注册成功'})
        except Exception as e:
            print(str(e))
            return Response({'errcode':3,'msg':'服务器错误'})

    # 登录
    def login(self, request):
        try:
            name = request.data.get('name')
            mobile = request.data.get("mobile")
            password = request.data.get("password")

            user_type = None
            user = ShopsModel.objects.filter(nickname=name,mobile=mobile, is_delete=False).first()
            if user:
                if user.is_apply == False:
                    return Response({"errcode": 2, "msg": "审核中！请耐心等待！"})
                user_type = 2

            user = SendModel.objects.filter(nickname=name,mobile=mobile, is_delete=False).first()
            if user:
                if user.is_apply == False:
                    return Response({'errcode': 2, 'msg': '审核中！请耐心等待！'})
                user_type = 1

            if not user_type:
                user = UserModel.objects.filter(nickname=name,mobile=mobile, is_delete=False).first()
                if not user:
                    return Response({"errcode": 3, "msg": "用户不存在！"})


            if check_password(password, user.password):
                user.last_login = datetime.datetime.now()  # 更新登录时间
                user.save()
                # 有权限登录站点

                myjwt = MyJwt()

                if user_type == 2:
                    ser = ShopsSer(user)
                elif user_type == 1:
                    ser = SendSer(user)
                else:
                    ser = UserSer(user)
                return Response({
                    "errcode": 0,
                    "message": "登录成功！",
                    "token": myjwt.encode({'id': user.id}),
                    "data": ser.data,
                    "user_type": user_type,
                })
            return Response({"errcode": 1, "msg": "用户名或密码错误！"})
        except Exception as e:
            print("错误", e)

    # 获取用户信息
    def userinfo(self, request):
        try:
            user_id = request.query_params.get('user_id')
            user_type = request.query_params.get('user_type')

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"errcode": 1, "msg": "用户不存在！"})
            if user_type != None:
                return Response({"errcode": 2, "msg": "非法请求！"})

            ser = UserSer(user)
            return Response({"errcode": 0, "msg": "ok！", "data": ser.data})
        except Exception as e:
            print("错误", e)
            return Response({'errcode':3,'msg':'服务器错误'})

    # 修改用户信息
    def update_info(self, request):

        user_id = request.data.get('user_id')

        nickname = request.data.get('nickname')
        mobile = request.data.get('mobile')
        password = request.data.get('password')

        try:
            flag = UserModel.objects.filter(nickname=nickname, is_delete=False).exclude(id=user_id).count()

            if flag != 0:
                return Response({'errcode':1,'msg':'用户数据重复'})

            user = UserModel.objects.filter(id=user_id, is_delete=False)

            if not user:
                return Response({'errcode':2,'msg':'用户不存在'})

            if nickname:
                user.update(nickname=nickname)
            if mobile:
                user.update(mobile=mobile)
            if password:
                hash_pwd = make_password(password,'pbkdf2_sha256')
                user.update(password=hash_pwd)
            return Response({'errcode':0,'msg':'修改成功'})
        except Exception as e:
            print(str(e))
            pass

    # 商家下的 商品分类和商品
    def shops_goods(self, request, pk):
        try:
            user = ShopsModel.objects.filter(id=pk, is_delete=False).first()

            goods_type = user.goodstypemodel_set.filter(is_delete=False)

            goods_type_ser = GoodTypeSer(goods_type, many=True)
            goods_type = json.loads(json.dumps(goods_type_ser.data))
            for i in goods_type:
                goods = GoodsModel.objects.filter(type_id=i["id"], is_delete=False).all()
                goods_ser = GoodSer(goods, many=True)
                goods = json.loads(json.dumps(goods_ser.data))
                i["goods_list"] = goods

            return Response({"errcode": 0, "msg": "ok！", "data": goods_type})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "nsg": "服务器错误！"})

# 地址管理
class AddressViewSet(ViewSet):

    # 获取用户地址
    def address_list(self, request):
        try:
            user_id = request.query_params.get('id')

            address = AddressModel.objects.filter(user_id=user_id, is_delete=False).all()
            ser = AddressSer(address, many=True)
            return Response({"errcode": 0, "msg": "ok！", "data": ser.data})
        except Exception as e:
            print("错误", e)
            pass

    # 添加地址
    def add(self, request):
        # try:
        user_id = request.data.get('user_id')

        nickname = request.data.get("nickname")
        mobile = request.data.get("mobile")
        address = request.data.get("address")
        is_default = request.data.get("is_default")

        if is_default == "true":
            AddressModel.objects.filter(user_id=user_id, is_delete=False).update(is_default=False)

        address_data = {
            "user": user_id,
            "nickname": nickname,
            "mobile": mobile,
            "address": address,
            "is_default": is_default,
        }
        serializer = AddressSer(data=address_data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response({"errcode": 0, "msg": "添加成功！"})
        # except Exception as e:
        #     print("错误", e)
        #     pass

    # 修改地址
    def update(self, request):
        try:
            user_id = request.data.get('user_id')

            id = request.data.get("add_id")
            nickname = request.data.get("nickname")
            mobile = request.data.get("mobile")
            address = request.data.get("address")
            is_default = request.data.get("is_default")

            address_dict = AddressModel.objects.filter(id=id, user_id=user_id, is_delete=False).first()
            if not address_dict:
                return Response({"errcode": 1, "message": "地址不存在！"})

            if is_default == "true":
                AddressModel.objects.filter(user_id=user_id, is_delete=False).update(is_default=False)

            address_data = {
                "id": id,
                "user": user_id,
                "nickname": nickname,
                "mobile": mobile,
                "address": address,
                "is_default": is_default,
            }
            serializer = AddressSer(instance=address_dict, data=address_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            return Response({"errcode": 0, "message": "修改成功！"})
        except Exception as e:
            print("错误", e)
            pass

    # 删除地址
    def delete(self, request, pk):
        try:
            user_id = request.query_params.get('id')

            address = AddressModel.objects.filter(id=pk, user_id=user_id, is_delete=False)
            if not address:
                return Response({"errcode": 1, "msg": "地址不存在！"})

            address.update(is_delete=True)

            return Response({"errcode": 0, "msg": "删除成功！"})
        except Exception as e:
            print("错误", e)
            pass

# 收藏和取消收藏
class CollectViewSet(ViewSet):

    # 添加收藏
    def add(self, request, pk):
        try:
            user_id = request.data.get('user_id')

            collect = CollectModel.objects.filter(user_id=user_id, shops_id=pk, is_delete=False)
            if collect:
                return Response({"errcode": 1, "msg": "已收藏！"})

            CollectModel.objects.create(user_id=user_id, shops_id=pk)
            return Response({"errcode": 0, "msg": "收藏成功！"})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 2, "msg": "服务器错误！"})

    # 取消收藏
    def delete(self, request, pk):
        try:
            user_id = request.query_params.get('user_id')

            collect = CollectModel.objects.filter(user_id=user_id, shops_id=pk, is_delete=False)
            if not collect:
                return Response({"errcode": 1, "message": "已取消收藏！"})

            CollectModel.objects.filter(user_id=user_id, shops_id=pk).delete()
            return Response({"errcode": 0, "msg": "取消收藏成功！"})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 2, "msg": "服务器错误！"})

# 订单
class OrderViewSet(ViewSet):
    myalipay = MyAlipay()

    # 创建订单
    def add_order(self, request):
        try:
            user_id = request.data.get("user_id")

            shops_id = request.data.get("shops_id")
            goods = request.data.get("goods")
            pay_method = request.data.get("pay_method")
            sum = request.data.get("sum")
            total_amount = request.data.get("total_amount")
            # remark = request.data.get("remark")
            address_id = request.data.get("address_id")

            goods = json.loads(goods)

            if not goods:
                return Response({"errcode": 1, "msg": "请先选择商品！"})


            pay_time = datetime.datetime.now().timestamp()
            # print('时间为》》》》》',pay_time)
            # 订单id
            order_id = str(pay_time * 1000000) + str(user_id) + str(random.randint(100000, 999999))

            order = OrderModel.objects.create(user_id=user_id,shops_id=shops_id,sum=sum,total_amount=total_amount,order_id=order_id,pay_method=pay_method,address_id=address_id)


            # print(goods)
            for i in goods:
                OrderGoodsModel.objects.create(order_id=order.id,goods_id=i['id'],sum=i["sum"],sum_price=i["sum_price"])

            return_url = "http://127.0.0.1:8080/index/order"
            url = self.myalipay.get_pay_url(order_id, total_amount, return_url)
            OrderModel.objects.update(pay_state=2)
            return Response({"errcode": 0, "msg": "ok！","url":url})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 2, "msg": "服务器错误！"})

    # 获取用户所有订单
    def get_order(self, request):
        try:
            user_id = request.query_params.get('user_id')

            order_list = OrderModel.objects.filter(user_id=user_id,is_delete=False).all()
            ser = OrderSer(order_list,many=True)
            order_list = ser.data
            order_list = json.loads(json.dumps(order_list))
            for i in order_list:
                i["is_comment"] = False
                comment = CommentModel.objects.filter(order_id=i["id"],is_delete=False)
                if comment:
                    i["is_comment"] = True
            return Response({"errcode": 0, "msg": "ok！","data": order_list})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "msg": "服务器错误！"})

    # 获取未支付的订单
    def check_order(self, request):
        try:
            user_id = request.query_params.get('user_id')

            order_list = OrderModel.objects.filter(user_id=user_id,pay_state=1,is_delete=False).all()
            ser = OrderSer(order_list,many=True)
            order_list = ser.data
            order_list = json.loads(json.dumps(order_list))
            return Response({"errcode": 0, "msg": "ok！","data": order_list})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "msg": "服务器错误！"})

    # 获取已支付的订单
    def order_check(self, request):
        try:
            user_id = request.query_params.get('user_id')

            order_list = OrderModel.objects.filter(user_id=user_id,pay_state=2,is_delete=False).all()
            ser = OrderSer(order_list,many=True)
            order_list = ser.data
            order_list = json.loads(json.dumps(order_list))
            return Response({"errcode": 0, "msg": "ok！","data": order_list})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "msg": "服务器错误！"})

    # 获取订单详情
    def order_desc(self, request, pk):
        try:
            # user_id = request.query_params.get('user_id')
            user_id = request.data.get('user_id')
            print(user_id)

            order = OrderModel.objects.filter(id=pk , user_id=user_id, is_delete=False).first()
            order_goods_list = order.ordergoodsmodel_set.all()

            goods_list = []
            for i in order_goods_list:
                goods = i.goods
                goods_ser = GoodSer(goods)
                goods = json.loads(json.dumps(goods_ser.data))
                order_goods = OrderGoodsSer(i)
                order_goods = json.loads(json.dumps(order_goods.data))
                goods["order"] = order_goods
                goods_list.append(goods)
            order_ser = OrderSer(order)
            order = order_ser.data
            return Response({"errcode": 0, "msg": "ok！", "order": order,"goods_list":goods_list})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "msg": "服务器错误！"})

    # 获取没有支付的订单的地址
    def not_order(self, request, pk):
        try:
            order = OrderModel.objects.filter(id=pk, pay_method=1, pay_state=1, is_delete=False).first()

            return_url = "http://127.0.0.1:8080/index/order/"
            pay_url = self.myalipay.get_pay_url(order.order_id, str(order.total_amount), return_url)

            order.pay_state = 1
            order.save()
            return Response({"errcode": 0, 'msg': '正在跳转支付地址', 'pay_url': pay_url})

        except Exception as e:
            print("获取没有支付的订单失败", e)
            return Response({"errcode": 1, 'msg': "跳转失败"})

# 评论
class CommentViewSet(ViewSet):

    # 获取所有商家评论
    def comment_list(self, request):

        id = request.query_params.get('id')
        # id = request.data.get('id')

        try:
            comment_list = CommentModel.objects.filter(shops_id=id, is_delete=False).all()
            comment_list = CommentSer(comment_list, many=True)
            comment_list = json.loads(json.dumps(comment_list.data))
            # comment_reply = []
            for i in comment_list:
                comment_reply = ReplyModel.objects.filter(comment_id=i["id"]).all()
                comment_reply = ReplySer(comment_reply, many=True)
                comment_reply = json.loads(json.dumps(comment_reply.data))

                i["reply"] = comment_reply
            return Response({"errcode": 0, "msg": "ok！", "comment": comment_list})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "msg": "服务器错误！"})

    # 发布评论
    def add_comment(self, request):
        try:
            user_id = request.data.get("user_id")
            shops_id = request.data.get("shops_id")
            order_id = request.data.get("order_id")
            content = request.data.get("content")
            print(user_id,shops_id,order_id,content)
            CommentModel.objects.create(user_id=user_id, shops_id=shops_id, order_id=order_id, content=content)

            return Response({"errcode": 0, "msg": "评论成功！"})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "msg": "服务器错误！"})

    # 发布回复评论
    def user_add(self, request):
        try:
            user_id = request.data.get("user_id")
            shops_id = request.data.get("shops_id")
            order_id = request.data.get("order_id")
            content = request.data.get("content")
            CommentModel.objects.create(user_id=user_id, shops_id=shops_id, order_id=order_id, content=content,
                                        is_reply=False)

            return Response({"errcode": 0, "msg": "评论成功！"})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "msg": "服务器错误！"})



